package io.github.lee.jel.ui.item.list

import android.app.Application
import com.chad.library.adapter4.BaseQuickAdapter
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.core.vm.BaseRefreshViewModel
import io.github.lee.jel.domain.Item
import io.github.lee.core.vm.err.DataParseFailedException
import io.github.lee.core.vm.err.NoMoreDataException
import io.github.lee.jel.err.ResponseFailException
import io.github.lee.jel.global.session
import io.github.lee.jel.repository.ItemRepository
import io.github.lee.jel.repository.query.QueryIncludeItemType
import io.github.lee.jel.repository.query.QuerySortBy
import javax.inject.Inject

@HiltViewModel
class ItemListVM @Inject constructor(
    application: Application,
    private val repo: ItemRepository
) : BaseRefreshViewModel<Item>(application) {

    var parentItem: Item? = null
    override fun onCreateAdapter(): BaseQuickAdapter<Item, *> = ItemListAdapter()


    //===Desc:=============================================================

    override fun onRefreshOrLoadMore(isRefresh: Boolean) {
        super.onRefreshOrLoadMore(isRefresh)
        if (isRefresh) {
            currentPage = 1
        } else {
            currentPage++
        }
        val includeItemTypes = when (parentItem?.collectionType) {
            "movies" -> {
                listOf(QueryIncludeItemType.Movie)
            }
            "tvshows" -> {
                listOf(QueryIncludeItemType.Series)
            }
            else -> {
                null
            }
        }
        launchResult(
            block = {
                repo.userItems(
                    mContext.session?.userId, parentItem?.id,
                    currentPage,
                    includeItemTypes = includeItemTypes,
                    sortBy = listOf(QuerySortBy.SortName)
                )
            },
            error = {
                it?.printStackTrace()
                error(it)
            }
        ) {
            if (!it.isSuccess) {
                currentPage--
//                refreshFail(ResponseFailException(it))
                error(ResponseFailException(it))
                return@launchResult
            }
            val data = it.data
            if (null == data) {
                currentPage--
                error(DataParseFailedException(mContext))
                return@launchResult
            }
            val items = data.items
            if (items.isNullOrEmpty()) {
                if (isRefresh) {
                    empty(NoMoreDataException(mContext))
                    refreshSuccess()
                } else {
                    loadMoreSuccess(false)
                }
            } else {
                if (isRefresh) {
                    submitList(items)
                    refreshSuccess()
                } else {
                    addAll(items)
                    loadMoreSuccess(true)
                }
            }

        }

    }
}